from django.conf import settings
from rest_framework.viewsets import ModelViewSet
from goods.models import GoodsChannel,GoodsChannelGroup, GoodsCategory,Brand
from meiduo_admin.my_paginate import MyPageNumberPagination
from meiduo_admin.good import brand_serializers
from rest_framework.generics import ListAPIView
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response

class BrandsViewSet(ModelViewSet):
    pagination_class=MyPageNumberPagination
    serializer_class = brand_serializers.BrandsViewSetSerializer
    queryset = Brand.objects.all()

 #2.重写create方法
    def create(self, request, *args, **kwargs):
        #1.获取参数
        logo=request.FILES.get("logo")
        name=request.data.get("name")
        first_letter=request.data.get("first_letter")

        #2.校验参数
        if not all([logo,name,first_letter]):
            return Response(status=403)
        #3.数据入库
        client= Fdfs_client(settings.FDFS_CONFIG)
        ret=client.upload_by_buffer(logo.read())

        #3.1判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        #3.2数据入库图片
        image_url=ret.get("Remote file_id")
        Brand.objects.create(name=name,logo=image_url,first_letter=first_letter)
        Brand.objects.filter(id=name,logo='').update(logo=image_url)


        #4.返回响应
        return Response(status=201)


        # 2.重写update方法

    def update(self, request, *args, **kwargs):
        #1.获取参数
        logo=request.FILES.get("logo")
        name=request.data.get("name")
        first_letter=request.data.get("first_letter")
        brand=self.get_object()

        #2.校验参数
        if not all([logo,name,first_letter]):
            return Response(status=403)
        #3.数据入库
        client= Fdfs_client(settings.FDFS_CONFIG)
        ret=client.upload_by_buffer(logo.read())

        #3.1判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        #3.2数据入库图片
        image_url=ret.get("Remote file_id")
        pk = self.kwargs.get("pk")
        # Brand.objects.create(name=name,logo=image_url,first_letter=first_letter)
        Brand.objects.filter(id=pk).update(logo=image_url,name=name,first_letter=first_letter)
        #方法二
        # brand.logo = image_url
        # brand.name = name
        # brand.first_letter = first_letter
        # brand.save()

        #4.返回响应
        return Response(status=201)